package com.hdl.linstener;

import javax.servlet.ServletContext;
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
import javax.servlet.annotation.WebListener;
import javax.servlet.http.HttpSessionAttributeListener;
import javax.servlet.http.HttpSessionBindingEvent;
import javax.servlet.http.HttpSessionEvent;
import javax.servlet.http.HttpSessionListener;

import com.hdl.service.NumService;
import com.hdl.service.impl.NumServiceImpl;

/**
 * Application Lifecycle Listener implementation class NumCountLinstener 在线人数监听器
 *
 */
@WebListener
public class NumCountLinstener implements ServletContextListener, HttpSessionListener, HttpSessionAttributeListener{

	private int count = 0;//访问总人数
    private int online = 0;//在线总人数
    private ServletContext application = null;

    private NumService service = new NumServiceImpl();//业务逻辑层

    public NumCountLinstener() {
    }


    public void contextInitialized(ServletContextEvent sce) {
        application = sce.getServletContext();

        //读取总人数
        System.out.println(service.getCount());
        count = service.getCount();
    }

    public void contextDestroyed(ServletContextEvent sce) {
        //关闭服务器时记录总人数
        service.saveCount(count);
    }



    public void sessionCreated(HttpSessionEvent se) {
        //创建会话时增加访问人数
        count++;
        online++;
        application.setAttribute("count",count);
        application.setAttribute("online",online);
    }

    public void sessionDestroyed(HttpSessionEvent se) {
        //回话结束时减少在线人数
        online--;
        application.setAttribute("online",online);
    }


    public void attributeAdded(HttpSessionBindingEvent sbe) {

    }

    public void attributeRemoved(HttpSessionBindingEvent sbe) {

    }

    public void attributeReplaced(HttpSessionBindingEvent sbe) {

    }
	
}
